package com.shiku.imserver.common.utils;

import com.shiku.imserver.common.constant.KConstants;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.lang3.StringUtils;
import org.tio.core.ChannelContext;

public class ImUtils {
    public static String parseResource(String jid) {
        if (jid == null) {
            return null;
        }
        int slashIndex = jid.indexOf(47);
        if (slashIndex + 1 > jid.length() || slashIndex < 0) {
            return "";
        }
        return jid.substring(slashIndex + 1);
    }

    public static String parseBareUserId(String jid) {
        int slashIndex = jid.indexOf(47);
        if (slashIndex < 0) {
            return jid;
        }
        if (slashIndex == 0) {
            return "";
        }
        return jid.substring(0, slashIndex);
    }

    public static String formatRegion(String region) {
        if (StringUtils.isBlank(region)) {
            return "";
        }
        String[] arr = StringUtils.split(region, "|");
        List<String> validArr = new ArrayList<>();
        for (String e : arr) {
            if (StringUtils.isNotBlank(e) && !KConstants.PAGE_INDEX.equals(e)) {
                validArr.add(e);
            }
        }
        if (validArr.size() == 0) {
            return "";
        }
        if (validArr.size() == 1) {
            return validArr.get(0);
        }
        return validArr.get(validArr.size() - 2) + validArr.get(validArr.size() - 1);
    }

    public static String formatUserAgent(ChannelContext channelContext) {
        return null;
    }

    public static void main(String[] args) {
        System.out.println(formatRegion("中国|杭州|铁通"));
    }
}
